using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using DG.Tweening;
using Newtonsoft.Json.Linq;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class Container : MonoBehaviour
{
    public Sprite[] leftBgSe;
    public Sprite[] centerBgSe;
    public Sprite[] rightBgSe;
    public Sprite[] repairBgSe;
    public Image leftBg;
    public Image centerBg;
    public Image rightBg;
    public Image repairBg;
    public GameObject frontObject;
    public GameObject backObject;
    public GameObject lockObject;
    public GameObject goodsPrefab;
    private int index;
    public bool isLock = false;
    private ValueTuple<int, int> columnAndRow;
    public GameObject repairObject;

    void Start()
    {
    }

    public void InitContainer(ValueTuple<int, int> car, int containerIndex, int containerPosId)
    {
        Debug.Log("初始化容器" + car + "Index" + containerIndex);
        ShowContainerBg(car);
        columnAndRow = car;

        index = containerIndex;

        lockObject.SetActive(isLock);
        repairObject.SetActive(false);
        if (containerPosId == 2)
        {
            isLock = true;
            lockObject.SetActive(isLock);
            GlobalEventManager.OnEvent("AdsPlaybackCompleted", OnAdsPlaybackCompleted);
        }
    }

    public void InitRepair(ValueTuple<int, int> car)
    {
        repairObject.SetActive(true);
        lockObject.SetActive(false);
        ShowContainerBg(car);

        repairBg.sprite = repairBgSe[Data.StyleId];
        repairBg.SetNativeSize();
    }

    private void ShowContainerBg(ValueTuple<int, int> car)
    {
        Debug.Log("显示容器背景" + car);
        int col = car.Item1;
        switch (col)
        {
            case 0:
                leftBg.transform.gameObject.SetActive(true);
                centerBg.transform.gameObject.SetActive(false);
                rightBg.transform.gameObject.SetActive(false);

                leftBg.sprite = leftBgSe[Data.StyleId];
                break;
            case 1:
                leftBg.transform.gameObject.SetActive(false);
                centerBg.transform.gameObject.SetActive(true);
                rightBg.transform.gameObject.SetActive(false);

                centerBg.sprite = centerBgSe[Data.StyleId];
                break;
            case 2:
                leftBg.transform.gameObject.SetActive(false);
                centerBg.transform.gameObject.SetActive(false);
                rightBg.transform.gameObject.SetActive(true);

                rightBg.sprite = rightBgSe[Data.StyleId];
                break;
        }
    }

    //前排
    public void InitFront()
    {
        if (Data.goodsData.Count <= 0) return;

        List<List<int>> layerArr = Data.goodsData[index];
        if (layerArr.Count <= 0) return;
        List<int> goodsArr = layerArr[layerArr.Count - 1];
        layerArr.RemoveAt(layerArr.Count - 1);

        for (int i = 0; i < goodsArr.Count; i++)
        {
            int goodsId = goodsArr[i];
            GameObject prefab = Instantiate(goodsPrefab);
            prefab.transform.SetParent(frontObject.transform.GetChild(i), false);
            Goods goods = prefab.GetComponent<Goods>();
            JObject customData = new JObject
            {
                { "goodsId", goodsId },
                { "index", i },
                { "isBack", false }
            };
            goods.container = this;
            goods.Init(customData);
        }
    }

    //后排
    public void InitBack()
    {
        if (Data.goodsData.Count <= 0) return;

        List<List<int>> layerArr = Data.goodsData[index];
        Debug.Log("layerArr" + layerArr.Count + "=====" + index);
        if (layerArr.Count <= 0) return;
        List<int> goodsArr = layerArr[layerArr.Count - 1];
        layerArr.RemoveAt(layerArr.Count - 1);

        for (int i = 0; i < goodsArr.Count; i++)
        {
            int goodsId = goodsArr[i];
            GameObject prefab = Instantiate(goodsPrefab);
            prefab.transform.SetParent(backObject.transform.GetChild(i), false);
            Goods goods = prefab.GetComponent<Goods>();
            JObject customData = new JObject
            {
                { "goodsId", goodsId },
                { "index", i },
                { "isBack", true }
            };
            goods.container = this;
            goods.Init(customData);
        }
    }

    //back转front
    public void BackToFront()
    {
        int isGoods = -1;  // 默认值 -1 表示没有找到
        for (int i = 0; i < frontObject.transform.childCount; i++)
        {
            Transform goodsC = frontObject.transform.GetChild(i);
            Transform goods = goodsC.Find("Goods");
            if (goods != null && goods.name == "Goods")
            {
                isGoods = i;  // 找到时返回索引
                break;  // 一旦找到就跳出循环
            }
        }

        // 如果没有找到 "Goods" 子物体
        if (isGoods < 0)
        {
            bool isBackToFront = false;

            // 遍历 back 中的每个子物体
            for (int i = 0; i < backObject.transform.childCount; i++)
            {
                Transform backContainer = backObject.transform.GetChild(i);
                Transform goods = backContainer.Find("Goods");

                if (goods != null)
                {
                    isBackToFront = true;

                    // 获取 Goods 组件
                    Goods goodsComponent = goods.GetComponent<Goods>();
                    if (goodsComponent != null)
                    {
                        // 将 Goods 移动到 front 的对应位置
                        goods.SetParent(frontObject.transform.GetChild(i));
                        goods.localPosition = Vector3.zero;
                        // 调用 Goods 中的方法
                        goodsComponent.SetFront();
                    }
                }
            }

            // 如果有 Goods 被移动到 front 层，初始化新的 back 层
            if (isBackToFront)
            {
                InitBack();
            }
        }
    }

    //消除前面的front
    public void ClearFront()
    {
        int goodsIndex = -1;
        bool isClear = true;

        // 遍历 front 中的每个子物体
        for (int i = 0; i < frontObject.transform.childCount; i++)
        {
            Transform backContainer = frontObject.transform.GetChild(i);
            Transform goods = backContainer.Find("Goods");

            if (goods != null)
            {
                Goods goodsComponent = goods.GetComponent<Goods>(); // 获取 Goods 组件
                if (goodsComponent != null)
                {
                    int index = goodsComponent.goodsId;
                    if (goodsIndex >= 0)
                    {
                        if (goodsIndex != index)
                        {
                            isClear = false;
                            break;
                        }
                    }
                    else
                    {
                        goodsIndex = index;
                    }
                }
            }
            else
            {
                isClear = false;
                break;
            }
        }

        if (isClear)
        {
            //有20%的几率合成新的食物
            // bool isEmergencyic = UserManager.Instance.GetUserInfo()["IsEmergencyic"].ToObject<bool>();
            // if (Data.clearCount == 1 || (Data.clearCount != 0 && UnityEngine.Random.Range(0, 100) < -1 && !isEmergencyic))
            // {
            //     Debug.Log("合成新的食物");
            //     GlobalEventManager.OnEvent("SynthesizeNewFood", OnSynthesizeNewFood);
            //     GlobalEventManager.OnEvent("EmergencyicBuySuccess", OnEmergencyicBuySuccess);
            //     PanelManager.Instance.OpenPanel<EmergencyicPanel>();
            //     // SynthesizeNewFood();
            //     return;
            // }
            StartCoroutine(ClearAndMoveCoroutine());
        }
        else
        {
            //判断是否空间不足
            var status = GameManager.Instance.GetGameStatus();
            if (status.isGameLose)
            {
                Tools.Log("判断游戏状态", "前排没有位置了");
                PanelManager.Instance.OpenPanel<RevivePanel>();
            }
            else if (status.isGameShuffle)
            {
                Tools.Log("判断游戏状态", "没有可消除的");
                PanelManager.Instance.OpenPanel<NoticePanel>();
            }
        }

    }

    private void OnEmergencyicBuySuccess()
    {
        StartCoroutine(ClearAndMoveCoroutine());
        GlobalEventManager.OffEvent("EmergencyicBuySuccess", OnEmergencyicBuySuccess);
        GlobalEventManager.OffEvent("SynthesizeNewFood", OnSynthesizeNewFood);
    }

    private void OnSynthesizeNewFood()
    {
        List<Goods> goodsToClean = new List<Goods>();
        int goodsType = -1;
        // 收集所有需要清除的 Goods
        foreach (Transform child in frontObject.transform)
        {
            Transform goods = child.Find("Goods");
            if (goods != null)
            {
                Goods goodsComponent = goods.GetComponent<Goods>();
                if (goodsComponent != null)
                {
                    goodsType = goodsComponent.goodsId;
                    goodsToClean.Add(goodsComponent);
                }
            }
        }

        Transform f1 = goodsToClean[0].transform;
        Transform f2 = goodsToClean[1].transform;
        Transform f3 = goodsToClean[2].transform;

        f1.DOMove(f2.position, 0.1f).OnComplete(() =>
        {
            StartCoroutine(f1.GetComponent<Goods>().SetClearCoroutine());
        });

        f3.DOMove(f2.position, 0.1f).OnComplete(() =>
        {
            StartCoroutine(f3.GetComponent<Goods>().SetClearCoroutine());

            int randomType = UnityEngine.Random.Range(0, Constants.GOODS_COUNT);
            f2.GetComponent<Goods>().ChangeGoods(randomType);
        });
        //记录消除的次数
        Data.clearCount++;
        GlobalEventManager.OffEvent("SynthesizeNewFood", OnSynthesizeNewFood);
        GlobalEventManager.OffEvent("EmergencyicBuySuccess", OnEmergencyicBuySuccess);
    }

    private IEnumerator ClearAndMoveCoroutine()
    {
        List<Goods> goodsToClean = new List<Goods>();
        int goodsType = -1;
        // 收集所有需要清除的 Goods
        foreach (Transform child in frontObject.transform)
        {
            Transform goods = child.Find("Goods");
            if (goods != null)
            {
                Goods goodsComponent = goods.GetComponent<Goods>();
                if (goodsComponent != null)
                {
                    goodsType = goodsComponent.goodsId;
                    goodsToClean.Add(goodsComponent);
                }
            }
        }

        // 创建一个协程列表来存储所有的 SetClear 操作
        List<Coroutine> clearCoroutines = new List<Coroutine>();

        // 同时启动所有 SetClear 操作
        foreach (Goods goods in goodsToClean)
        {
            clearCoroutines.Add(StartCoroutine(goods.SetClearCoroutine()));
        }

        // 等待所有 SetClear 操作完成
        foreach (Coroutine coroutine in clearCoroutines)
        {
            yield return coroutine;
        }

        // 执行 BackToFront
        BackToFront();
        //消除的goods类型
        Debug.Log("消除的goods类型" + goodsType);
        //记录消除的次数
        Data.clearCount++;

        //如果是购物车玩法
        if (Data.mode == 0)
        {
            // List<Goods> allGoods = GoodsManager.Instance.GetAllGoods();
            // Debug.Log("所有商品" + allGoods.Count);
            // if (allGoods.Count <= 0)
            // {
            //     // 游戏通关
            //     Debug.Log("游戏通关");
            //     CountdownManager.Instance.Stop(); // 停止倒计时
            //     int guide = PlayerPrefs.GetInt("Guide", 0);
            //     if (guide == 0 && Data.mode == 0)
            //     {
            //         GuideManager.Instance.Zhuhe();
            //     }
            //     else
            //     {
            //         PanelManager.Instance.OpenPanel<PassPanel>();
            //     }
            // }
            // else
            // {
            //     //判断是否空间不足
            //     var status = GameManager.Instance.GetGameStatus();
            //     if (status.isGameLose)
            //     {
            //         Tools.Log("判断游戏状态", "前排没有位置了");
            //         PanelManager.Instance.OpenPanel<RevivePanel>();
            //     }
            //     else if (status.isGameShuffle)
            //     {
            //         Tools.Log("判断游戏状态", "没有可消除的");
            //         PanelManager.Instance.OpenPanel<NoticePanel>();
            //     }
            // }

            //订单判断
            // GlobalEventManager.EmitEvent<int>("OrderElimination", goodsType);
        }
        else if (Data.mode == 1)
        {
            // 判断限时模式是否通关
            GlobalEventManager.EmitEvent<int>("TypesOfElimination", goodsType);
        }


    }



    //移除GoodsC所有的子节点
    public void RemoveGoodsCAllChild()
    {
        foreach (Transform child in frontObject.transform)
        {
            Transform goods = child.Find("Goods");
            if (goods != null)
            {
                goods.SetParent(null);
                Destroy(goods.gameObject);
            }
        }
        foreach (Transform child in backObject.transform)
        {
            Transform goods = child.Find("Goods");
            if (goods != null)
            {
                goods.SetParent(null);
                Destroy(goods.gameObject);
            }
        }
    }

    public void OnLockClick()
    {
        if (isLock)
        {
            //看广告解锁
            bool st = AdsManager.Instance.IsRewardedAdReady();
            if (st)
            {
                Data.car = columnAndRow;
                AdsManager.Instance.ShowRewardedAd();
            }
            else
            {
                Tools.ShowTipToast("Ad is not Ready");
            }
        }
    }

    public void OnAdsPlaybackCompleted()
    {
        Debug.Log("广告播放完成");
        if (Data.car == columnAndRow)
        {
            isLock = false;
            lockObject.SetActive(isLock);
        }
    }

    //判断当前的container的front 是否为空
    public bool IsFrontEmpty()
    {
        for (int i = 0; i < frontObject.transform.childCount; i++)
        {
            Transform goods = frontObject.transform.GetChild(i).Find("Goods");
            if (goods != null)
            {
                return false;
            }
        }
        return true;
    }

    public void ChangeContainerStyle()
    {
        leftBg.sprite = leftBgSe[Data.StyleId];

        centerBg.sprite = centerBgSe[Data.StyleId];

        rightBg.sprite = rightBgSe[Data.StyleId];

        repairBg.sprite = repairBgSe[Data.StyleId];
        repairBg.SetNativeSize();
    }

    void OnDestroy()
    {
        GlobalEventManager.OffEvent("AdsPlaybackCompleted", OnAdsPlaybackCompleted);
    }
}
